package com.twotwoshop.fegin.api.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Configuration
public class FeignInterceptor implements RequestInterceptor {

        @Override
        public void apply(RequestTemplate requestTemplate) {
            // 获取当前请求的上下文
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                // 获取请求头中的token
                String authorization = request.getHeader("Authorization");
                if (StringUtils.isNotBlank(authorization) && authorization.startsWith("Bearer ")) {
                    authorization = authorization.substring(7);
                }

                // 判断token是否存在并且不为空
                if (StringUtils.isNotBlank(authorization)) {
                    // 将token添加到feign请求头中
                    requestTemplate.header("Authorization", "Bearer " + authorization);
                }else {
                    requestTemplate.header("Authorization", "Bearer " + "31904217-bebe-4b13-8bb7-3675a63f444a");
                }
            }
        }

        // 日志级别
        @Bean
        Logger.Level feignLoggerLevel() {
            return Logger.Level.FULL;
        }
}